package common

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"note.zhiwangyunchuang.com/model"
)

var DB *gorm.DB

func InitDb() *gorm.DB {
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	userName := viper.GetString("datasource.userName")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true", userName, password, host, port, database, charset)
	fmt.Println("args=======>", args)
	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic("数据库链接失败" + err.Error())
	}
	fmt.Println("数据库链接成功", db)
	db.AutoMigrate(&model.Note{})
	db.AutoMigrate(&model.User{})
	db.LogMode(true)
	DB = db
	return db
}

func GetDb() *gorm.DB {
	return DB
}
